import type { Context } from "koa";
import errorType from "../constants/error-types.ts";

const errorHandler = (error: Error, ctx: Context) => {
  let status, message;

  switch (error.message) {
    case errorType.USER_OR_PASSWORD_IS_NOT_EMPTY:
      status = 202;
      message = "用户名或者密码不能为空~";
      break;
    case errorType.USER_IS_EXISIT:
      status = 202;
      message = "用户名已经存在~";
      break;
    case errorType.USER_DOES_NOT_EXISIT:
      status = 202;
      message = "用户名不存在~";
      break;
    case errorType.PASSWORD_IS_ERROR:
      status = 202;
      message = "用户登录密码错误~";
      break;
    case errorType.NOT_AUTHORIZATION:
      status = 202;
      message = "无效token~";
      break;
    case errorType.NOT_PERMISSION:
      status = 401;
      message = "您不具备操作权限 ~";
      break;
    default:
      status = 404;
      message = "NOT FOUND";
  }

  ctx.status = status;
  ctx.body = {
    success: false,
    data: {
      state: status,
      message,
      stack: process.env.NODE_ENV === "development" ? error.stack : undefined, // 开发环境返回堆栈信息
    },
  };
};

export default errorHandler;
